<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-4xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">通知 API</h1>
        <p class="text-gray-300 text-lg">
          向用户发送桌面通知，支持自定义图标、标题和操作按钮
        </p>
      </div>

      <!-- 权限状态 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">通知权限</h2>
        
        <div class="flex items-center justify-between mb-6">
          <div>
            <p class="text-gray-300 mb-2">当前权限状态:</p>
            <span
              :class="{
                'text-green-400': permission === 'granted',
                'text-yellow-400': permission === 'default',
                'text-red-400': permission === 'denied'
              }"
              class="font-semibold text-lg"
            >
              {{ getPermissionText(permission) }}
            </span>
          </div>
          
          <button
            v-if="permission !== 'granted'"
            @click="requestPermission"
            :disabled="permission === 'denied'"
            class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-notification mr-2"></i>
            请求权限
          </button>
        </div>

        <div v-if="permission === 'denied'" class="p-4 bg-red-900/30 border border-red-600 rounded-lg">
          <p class="text-red-400">
            通知权限已被拒绝。请在浏览器设置中手动启用通知权限。
          </p>
        </div>
      </div>

      <!-- 通知发送区域 -->
      <div v-if="permission === 'granted'" class="tech-card mb-8">
        <h3 class="text-xl font-semibold mb-6 text-white">发送通知</h3>
        
        <div class="space-y-6">
          <!-- 基本通知 -->
          <div class="bg-gray-800 rounded-lg p-6">
            <h4 class="text-lg font-semibold text-white mb-4">基本通知</h4>
            <div class="flex gap-4">
              <button
                @click="sendBasicNotification"
                class="tech-button"
              >
                <i class="i-carbon-notification mr-2"></i>
                发送基本通知
              </button>
              <button
                @click="sendNotificationWithIcon"
                class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-colors"
              >
                <i class="i-carbon-image mr-2"></i>
                带图标通知
              </button>
            </div>
          </div>

          <!-- 自定义通知 -->
          <div class="bg-gray-800 rounded-lg p-6">
            <h4 class="text-lg font-semibold text-white mb-4">自定义通知</h4>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
              <div>
                <label class="block text-gray-300 mb-2">标题:</label>
                <input
                  v-model="customNotification.title"
                  type="text"
                  placeholder="通知标题"
                  class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2"
                >
              </div>
              <div>
                <label class="block text-gray-300 mb-2">标签:</label>
                <input
                  v-model="customNotification.tag"
                  type="text"
                  placeholder="通知标签"
                  class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2"
                >
              </div>
            </div>
            
            <div class="mb-4">
              <label class="block text-gray-300 mb-2">内容:</label>
              <textarea
                v-model="customNotification.body"
                placeholder="通知内容"
                rows="3"
                class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2"
              ></textarea>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
              <div>
                <label class="block text-gray-300 mb-2">图标 URL:</label>
                <input
                  v-model="customNotification.icon"
                  type="url"
                  placeholder="https://example.com/icon.png"
                  class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2"
                >
              </div>
              <div>
                <label class="block text-gray-300 mb-2">图片 URL:</label>
                <input
                  v-model="customNotification.image"
                  type="url"
                  placeholder="https://example.com/image.jpg"
                  class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2"
                >
              </div>
            </div>
            
            <div class="flex items-center gap-6 mb-4">
              <label class="flex items-center text-gray-300">
                <input
                  v-model="customNotification.requireInteraction"
                  type="checkbox"
                  class="mr-2"
                >
                需要用户交互
              </label>
              <label class="flex items-center text-gray-300">
                <input
                  v-model="customNotification.silent"
                  type="checkbox"
                  class="mr-2"
                >
                静默通知
              </label>
            </div>
            
            <button
              @click="sendCustomNotification"
              class="tech-button"
            >
              <i class="i-carbon-send mr-2"></i>
              发送自定义通知
            </button>
          </div>

          <!-- 预设通知模板 -->
          <div class="bg-gray-800 rounded-lg p-6">
            <h4 class="text-lg font-semibold text-white mb-4">预设模板</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              <button
                v-for="template in notificationTemplates"
                :key="template.name"
                @click="sendTemplateNotification(template)"
                class="bg-gray-700 hover:bg-gray-600 text-white p-4 rounded-lg transition-colors text-left"
              >
                <div class="flex items-center mb-2">
                  <i :class="template.icon" class="text-xl mr-3"></i>
                  <span class="font-semibold">{{ template.name }}</span>
                </div>
                <p class="text-gray-300 text-sm">{{ template.description }}</p>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 通知历史 -->
      <div v-if="notificationHistory.length > 0" class="tech-card mb-8">
        <h3 class="text-xl font-semibold mb-4 text-white">通知历史</h3>
        
        <div class="space-y-3 max-h-64 overflow-y-auto">
          <div
            v-for="(notification, index) in notificationHistory.slice().reverse()"
            :key="index"
            class="bg-gray-800 rounded-lg p-4"
          >
            <div class="flex justify-between items-start">
              <div class="flex-1">
                <h5 class="text-white font-semibold">{{ notification.title }}</h5>
                <p class="text-gray-300 text-sm mt-1">{{ notification.body }}</p>
                <p class="text-gray-400 text-xs mt-2">{{ formatTime(notification.timestamp) }}</p>
              </div>
              <span
                :class="{
                  'bg-green-600': notification.status === 'sent',
                  'bg-red-600': notification.status === 'failed'
                }"
                class="px-2 py-1 rounded text-xs text-white"
              >
                {{ notification.status === 'sent' ? '已发送' : '失败' }}
              </span>
            </div>
          </div>
        </div>
        
        <div class="mt-4 pt-4 border-t border-gray-700">
          <button
            @click="clearHistory"
            class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
          >
            <i class="i-carbon-trash-can mr-1"></i>
            清空历史
          </button>
        </div>
      </div>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>Chrome 22+, Firefox 22+, Safari 7+, Edge 14+</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">主要属性</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">Notification.permission</code> - 获取权限状态</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">Notification.requestPermission()</code> - 请求权限</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">new Notification(title, options)</code> - 创建通知</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">通知选项</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><strong>body</strong> - 通知正文内容</li>
              <li><strong>icon</strong> - 通知图标</li>
              <li><strong>image</strong> - 通知图片</li>
              <li><strong>tag</strong> - 通知标签（用于替换相同标签的通知）</li>
              <li><strong>requireInteraction</strong> - 是否需要用户交互才能关闭</li>
              <li><strong>silent</strong> - 是否静默通知</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>新消息和聊天通知</li>
              <li>系统状态和任务完成提醒</li>
              <li>重要事件和截止日期提醒</li>
              <li>实时更新和新闻推送</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 类型定义
interface NotificationTemplate {
  name: string
  description: string
  icon: string
  title: string
  body: string
  options: NotificationOptions
}

interface NotificationRecord {
  title: string
  body: string
  timestamp: number
  status: 'sent' | 'failed'
}

// 响应式状态
const permission = ref<NotificationPermission>('default')
const notificationHistory = ref<NotificationRecord[]>([])

const customNotification = ref({
  title: '自定义通知',
  body: '这是一个自定义的通知消息',
  icon: '',
  image: '',
  tag: '',
  requireInteraction: false,
  silent: false
})

// 通知模板
const notificationTemplates: NotificationTemplate[] = [
  {
    name: '欢迎通知',
    description: '欢迎新用户',
    icon: 'i-carbon-user',
    title: '欢迎使用 MDN API 演示',
    body: '感谢您体验我们的通知功能！',
    options: {
      icon: '🎉',
      tag: 'welcome'
    }
  },
  {
    name: '任务完成',
    description: '任务完成提醒',
    icon: 'i-carbon-checkmark',
    title: '任务已完成',
    body: '您的任务已成功完成，请查看结果。',
    options: {
      icon: '✅',
      tag: 'task-complete',
      requireInteraction: true
    }
  },
  {
    name: '系统警告',
    description: '重要系统消息',
    icon: 'i-carbon-warning',
    title: '系统警告',
    body: '检测到重要的系统事件，请及时处理。',
    options: {
      icon: '⚠️',
      tag: 'system-warning',
      requireInteraction: true
    }
  },
  {
    name: '新消息',
    description: '收到新消息',
    icon: 'i-carbon-chat',
    title: '新消息',
    body: '您有一条新消息，点击查看详情。',
    options: {
      icon: '💬',
      tag: 'new-message'
    }
  },
  {
    name: '静默通知',
    description: '不发出声音的通知',
    icon: 'i-carbon-volume-mute',
    title: '静默通知',
    body: '这是一个静默通知，不会发出声音。',
    options: {
      icon: '🔇',
      tag: 'silent',
      silent: true
    }
  },
  {
    name: '定时提醒',
    description: '定时任务提醒',
    icon: 'i-carbon-time',
    title: '定时提醒',
    body: '您设置的定时任务时间到了！',
    options: {
      icon: '⏰',
      tag: 'timer',
      requireInteraction: true
    }
  }
]

// 初始化
onMounted(() => {
  if ('Notification' in window) {
    permission.value = Notification.permission
  }
})

// 获取权限状态文本
const getPermissionText = (perm: NotificationPermission): string => {
  switch (perm) {
    case 'granted':
      return '已授权'
    case 'denied':
      return '已拒绝'
    case 'default':
      return '未设置'
    default:
      return '未知'
  }
}

// 请求通知权限
const requestPermission = async () => {
  if ('Notification' in window) {
    const result = await Notification.requestPermission()
    permission.value = result
  }
}

// 发送基本通知
const sendBasicNotification = () => {
  sendNotification('基本通知', '这是一个基本的桌面通知示例')
}

// 发送带图标的通知
const sendNotificationWithIcon = () => {
  sendNotification('带图标通知', '这个通知包含了一个图标', {
    icon: '🚀'
  })
}

// 发送自定义通知
const sendCustomNotification = () => {
  const options: NotificationOptions = {
    body: customNotification.value.body,
    requireInteraction: customNotification.value.requireInteraction,
    silent: customNotification.value.silent
  }

  if (customNotification.value.icon) {
    options.icon = customNotification.value.icon
  }

  if (customNotification.value.image) {
    (options as any).image = customNotification.value.image
  }

  if (customNotification.value.tag) {
    options.tag = customNotification.value.tag
  }

  sendNotification(customNotification.value.title, customNotification.value.body, options)
}

// 发送模板通知
const sendTemplateNotification = (template: NotificationTemplate) => {
  sendNotification(template.title, template.body, template.options)
}

// 通用发送通知方法
const sendNotification = (title: string, body: string, options: NotificationOptions = {}) => {
  try {
    if (permission.value !== 'granted') {
      throw new Error('通知权限未授权')
    }

    const notification = new Notification(title, {
      body,
      ...options
    })

    // 添加事件监听器
    notification.onclick = () => {
      console.log('通知被点击')
      notification.close()
    }

    notification.onshow = () => {
      console.log('通知已显示')
    }

    notification.onclose = () => {
      console.log('通知已关闭')
    }

    notification.onerror = () => {
      console.error('通知发送失败')
    }

    // 记录到历史
    notificationHistory.value.push({
      title,
      body,
      timestamp: Date.now(),
      status: 'sent'
    })

    // 自动关闭通知（5秒后）
    setTimeout(() => {
      notification.close()
    }, 5000)

  } catch (error) {
    console.error('发送通知失败:', error)
    
    // 记录失败到历史
    notificationHistory.value.push({
      title,
      body,
      timestamp: Date.now(),
      status: 'failed'
    })
  }
}

// 格式化时间
const formatTime = (timestamp: number): string => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

// 清空历史记录
const clearHistory = () => {
  notificationHistory.value = []
}
</script>
